<template>
 <view class="flex-1 mx-3 mt-3">
	 <view class="pt-3 px-3 bg-white" style="border-radius: 20rpx;border-top-width: 0px;box-shadow: 0px 2px 12px rgba(199, 196, 196, 0.3);" :style="{'border-top-color1':$em.$getThemeStyle(['br-color-mian'])['border-top-color']}" > 
		 <textarea  style="font-size: 28rpx;height: 260rpx;width: 100%;"
		 placeholder-style="color:#9E9E9E" v-model="content" maxlength="300"
		 placeholder="总想知道你现在的想法..."></textarea>
		<view class="flex flex-row flex-1 flex-wrap justify-between " style="animation: 1s all;"> 
			<view v-for="(val,index2) in pushImagesList" :key="index2" style="animation: 1s all;" @click="showImages(pushImagesList,index2)" class="rounded mb-2">
				<image style="width: 200rpx;height: 200rpx;border: 2px solid #F6F6F6;" class="rounded" mode="aspectFill" :src="config.imgUrl + val"></image>
				<!-- <view class="position-absolute-full align-center justify-center"  @click="deleteItem(pushImagesList,index2)">
					<view style="width: 50rpx;height: 50rpx;border-radius: 50rpx;background-color: rgba(0,0,0,0.5);" class="align-center justify-center">
						<em-icon style=" font-size: 32rpx;color: #FFFFFF;" :unicode="'\uec2a'"></em-icon>
					</view>
				</view> -->
				<view class="position-absolute top-0 right-0 "  @click.stop="deleteItem(pushImagesList,index2)">
					<view style="width: 40rpx;height: 40rpx;background-color: #FF4B1C;border-bottom-left-radius: 20rpx;margin: 2px;" class="align-center justify-center rounded-top-right">
						<em-icon style=" font-size: 24rpx;color: #FFFFFF;line-height: 24rpx;" :unicode="'\uec2a'"></em-icon>
					</view>
				</view>
			</view>
			<view v-if="pushImagesList.length>0" class="rounded mb-2" style="width: 200rpx;height: 200rpx;background-color: #F6F6F6;" @click="addAlbum('images')">
				<view class="position-absolute-full align-center justify-center">
					<!-- <view style="width: 50rpx;height: 50rpx;border-radius: 50rpx;background-color: rgba(0,0,0,0.5);" class="align-center justify-center mb-1">
						<em-icon style=" font-size: 32rpx;color: #FFFFFF;" :unicode="'\uea12'"></em-icon>
					</view>
					<text style="font-size: 26rpx;color: rgba(0,0,0,0.5)" class="mb-1 font-weight-bold">图片</text> -->
					<em-icon style="font-size: 50rpx;color: #AEACB9;" :unicode="'\uee66'"></em-icon> 
				</view>
			</view> 
			<view style="width: 200rpx;"></view>
			<view style="width: 200rpx;"></view>
		</view> 
	 </view>
 		
 		<view class="bg-white rounded py-2" style="margin-top: 2px;border-radius: 20rpx;">
 			<view class="flex-1 mx-3 flex-row justify-between align-end" style="border-radius: 45px;">
 				<view style="margin-right: 0px;">
 					<view class="flex flex-row align-center" @click="addAlbum('images')">
 						<view class="flex flex-row align-center justify-center pr-2">
 							<em-icon style="font-size: 50rpx;color: #AEACB9;" :unicode="'\uee66'"></em-icon> 
 						</view>
 					</view>
 				</view>
 				<view style="margin-right: 0px;">
 					<view @click="create()" class=" px-3 py-1 flex flex-row justify-center"  style="border-radius: 100rpx;" :style="[$em.$getThemeStyle(['bg-color-mian'])]">
 						<text class="font-28 text-white">发布</text>
 					</view>
 				</view>
 			</view>					
 		</view>
		<em-menus-bottom-popup ref="confirm"/> 
 </view>
</template>

<script>
  import {
    mapState
  } from 'vuex'
 let app = {}
  // #ifdef MP-WEIXIN || MP-KUAISHOU
  app = getApp({ allowDefault: true}).$vm
  // #endif
  // #ifdef APP-PLUS || H5
  app = getApp({allowDefault: true})
  // #endif

// #ifdef APP-PLUS
	const animation = weex.requireModule('animation');
	const videframe = uni.requireNativePlugin("sn-videoframe");
	const dom = uni.requireNativePlugin('dom')
// #endif
 //import mpHtml from '@/components/mp-html/mp-html'
 //import pushBtns from './components/push-btns'
 //import specPopup from './components/spec-popup'
  export default {
	components: {
		//pushBtns,mpHtml,specPopup
	},
    data() {
      return {
		scrollTop:0,
		pushStatus:null,//idle pushing done
		itemList:[],
		pushImagesList:[],
		pushVideoList:[],
		pushPosterList:[],
		content:"",
		subGoods:[],
		goodsList:[],
		id:0,
		form:{
			name:""
		},
		details:{}
      }
    },
    computed: {
      ...mapState([
        'systemInfo',
		'config',
		'userInfo'
      ]),
	  canSend(){
		return true  
	  },
      pageStyles() {
        return {
          wrap: app.$getThemeStyle(['bg-color--1'])
        }
      },
      headerStyles() {
        return {
          wrap: {
            ...app.$getThemeStyle(['bg-color-1', 'shadow-0']),
            'opacity': this.headerOpacity
          },
          title: {
            ...app.$getThemeStyle(['color-1']),
            'opacity': this.headerOpacity
          }
        }
      },
	  addBtns() {
	   return {
	     iconUnicode: '\uea12',
	     styles: {
	       btn: app.$getThemeStyle(['bg-color-103']),
	       icon: app.$getThemeStyle(['color-9'])
	     }
	   }
	  },
	  pushingBtns() {
	   return {
	     iconUnicode: '\ueec3',
	     styles: {
	       btn: app.$getThemeStyle(['bg-color-103']),
	       icon: app.$getThemeStyle(['color-103'])
	     }
	   }
	  },
	  headerLeftBtns() {
	    return [{
	      iconUnicode: '\uea64',
	      styles: {
	        btn: app.$getThemeStyle(['bg-color-102']),
	        icon: app.$getThemeStyle(['color-102'])
	      }
	    }]
	  },
      headerRightBtns() {
        return [{
          name: 'cart',
          iconUnicode: '\uf0b1',
          styles: {
            btn: app.$getThemeStyle(['bg-color-101']),
            icon: app.$getThemeStyle(['color-101'])
          }
        }]
      },
    },
	filters:{
	},
    async created() {
      this.$em = app.$em
	  await this.$nextTick()
    },
    onLoad(e) {
    },
	onShow() {
		//this.content = uni.getStorageSync("MP-HTML-EDIT") || ""
	},
    methods: {
	  showImages(images,index){
	  	   uni.previewImage({
	  	        urls:  images.map(image => this.config.imgUrl + image), // 图片列表的url数组
	  	        current: index, // 当前图片的索引
	  	        loop: true, // 是否开启循环预览
	  	        longPressActions: { // 可选的长按菜单操作
	  	          itemList: ['发送给朋友', '保存图片'],
	  	          success: res => {
	  	            console.log(res.tapIndex)
	  	          }
	  	        }
	  	      })
	  },
	  async addGoods(){
	  	this.$refs['goods-popup'].open({
	  		confirm:async (res)=>{
	  			for (let i = 0; i < res.length; i++) {
	  				let item = res[i];
					this.goodsList.push(item)
	  			/* 	uni.Chat.send("messageToRoom",{
	  					room_id:this.roomId,
	  					url:item.pic,
	  					content:"给您挑选了一款商品,赶紧去看看吧!",
	  					type:"goods",
	  					ext:{
	  						path:'/pages/goods/goods?id='+item.id
	  					}
	  				}) */
	  			}
	  			console.log(res)
	  		}
	  	})
	  },
	  addAlbum(){
	  	let _this = this
		uni.hideKeyboard()
	  		let menus = [];
	  		/* if(this.pushVideoList.length == 0){
	  			menus.push({
	  				name:"添加视频",
	  				event:()=>{
	  					this.$refs.confirm.close();
	  					uni.chooseVideo({  //打开选择视频 
	  						compressed:false,
	  						sourceType: ['album'],  //直接打开选择视频 ['album','camera'] 就会弹出选框
	  						success: function (res) {
	  							//_this.upload(res.tempFilePath,'videos')
	  							
	  							uni.html5appVideoCrop({
	  								url:plus.io.convertLocalFileSystemURL(res.tempFilePath),
	  								//ratio:res.width>res.height?"9/16":"16/9", 
	  								mode:res.width>res.height?"fill":"scale", 
	  								
	  							},(res1)=>{
	  								console.log("res",res1)
	  								_this.upload(res1.image,'videoAndThumb',{
	  									size:res.size,
	  									duration:res.duration,
	  									width:res.width,
	  									height:res.height,
	  									outPath:res1.mp4
	  									//outPath:res.tempFilePath
	  								})
	  							})
	  							return
	  							
	  						}
	  					})
	  					
	  				}					
	  			})
	  		} */
			menus.push({
					name:"添加图片",
					//iconUnicode:'\uea58',
					event:()=>{
						this.$refs.confirm.close();
						uni.chooseImage({
							count: 9,  
							sizeType: ['compressed'], 
							sourceType: ['album'],
							success: function  (res) {
								res.tempFilePaths.map((val)=>{
									_this.upload(val,'images')
								})
							}
						})	
					}			
			})
			this.$refs.confirm.open({
				menus:menus,		  
				duration:3000,
				confirm:()=>{}		  
			})
	  },
	  addAlbum1(type = ""){
	  	let _this = this
		if(type == "poster"){
			uni.chooseImage({
				count: 1,  
				sizeType: ['compressed'], 
				sourceType: ['album'],
				success: function  (res) {
					res.tempFilePaths.map((val)=>{
						_this.upload(val,type)
					})
				}
			})	
			return;
		}
		if(type == "images"){
			uni.chooseImage({
				count: 99,  
				sizeType: ['compressed'], 
				sourceType: ['album'],
				success: async (res)=> {
					let filePaths = res.tempFilePaths
					 for (let i = 0; i < filePaths.length; i++) {
					     this.upload(filePaths[i]);
						 await uni.sleep(500)
					  }
					/* res.tempFilePaths.map((val)=>{
						_this.upload(val,type)
					}) */
				}
			})	
			return;
		}
		
		
		let menus = [];
		if(this.pushVideoList.length == 0){
			menus.push({
				name:"添加视频",
				event:()=>{
					this.$refs.confirm.close();
					uni.chooseVideo({  //打开选择视频 
						compressed:false,
						sourceType: ['album'],  //直接打开选择视频 ['album','camera'] 就会弹出选框
						success: function (res) {
							//_this.upload(res.tempFilePath,'videos')
							videframe.getFrame({
							    url: res.tempFilePath,
								time:2,
							 },(e) => {
							    if (e.code == 0) {
								  _this.upload(e.imagePath,'videoAndThumb',{
								  	size:res.size,
								  	duration:res.duration,
								  	width:res.width,
								  	height:res.height,
									outPath:res.tempFilePath
								  })  
							    }else{
							      uni.showToast({title: e.msg, icon: "none"});
							    }            
							 })
							
						}
					})
					
				}					
			})
		}
		
		menus.push({
				name:"添加图片",
				//iconUnicode:'\uea58',
				event:()=>{
					this.$refs.confirm.close();
					uni.chooseImage({
						count: 9,  
						sizeType: ['compressed'], 
						sourceType: ['album'],
						success: function  (res) {
							res.tempFilePaths.map((val)=>{
								_this.upload(val)
							})
						}
					})	
				}			
		})
		this.$refs.confirm.open({
			menus:menus,		  
			duration:3000,
			confirm:()=>{}		  
		})
		
	  	 
	  },
	  async upload(path,type="images",info = {}){
	  	const res = await uni.$http.upload("/api/user/upload",{},path)
	  	if(!res.data)return;
		if(type == 'images'){
			this.pushImagesList.push(res.data.url)
			
		}
		if(type == 'videoAndThumb'){
			info.thumb = res.data.url;
			this.upload(info.outPath,'videos',info)
			delete info.outPath
		}
	  	if(type == 'videos'){
	  		this.pushVideoList.push({
				url:res.data.url,
				...info
			})
	  	}
	  	if(this.pushVideoList.length || this.pushImagesList.length){
	  		this.pushStatus = 'idle'
	  	}
	  	console.log("res",this.pushImagesList)
		this.$forceUpdate()
	  },
	  deleteItem(list,index){
		list.splice(index,1);
	  	if(!this.pushVideoList.length && !this.pushImagesList.length){
	  		this.pushStatus = null
	  	}
	  },
      scroll(e) {
        let scrollTop = e.scrollTop <= 0 ? 0 : e.scrollTop
        let transparentHeight = (this.systemInfo.windowWidth * 0.68 + this.systemInfo.statusBarHeight) / 2
        let opacityCoefficient = scrollTop / transparentHeight
        let opacity = opacityCoefficient > 1 ? 1 : opacityCoefficient
        //this.headerOpacity = opacity
        if (e.scrollBottom <= 250) {
         // this.loadmore()
        }
      },
	  getComponentRect(refs){  	 
		return  new Promise((resolve, reject) => {
			dom.getComponentRect(refs, rect => {
			     resolve(rect.size.height)
			   })
			})	  
	  },
	 async create(){
		
			if(this.pushImagesList.length == 0 && this.pushVideoList.length == 0){
				uni.showToast({
				  icon: 'none',
				  title: '您未上传任何图片或视频哦'
				})
				return
			}
			let params = {
				images:this.pushImagesList.join(","),
				videos:JSON.stringify(this.pushVideoList),
				content:this.content
			}
			console.log("this.goodsList",this.goodsList)
			if(this.goodsList.length>0){
				params.gid = this.goodsList[0].id
			}
			
			 uni.$http.post("/api/circle/push",params)
			 .then(()=>{
				this.pushImagesList = []
				this.content = ""
				this.$emit("published",{})
				setTimeout(()=>{
					uni.showToast({
					  icon: 'none',
					  title: '添加成功'
					})
				},0) 
			 })
			 .catch(err=>{
			 })
			
			
	 },
     async clickHeaderBtn(e) {
		  console.log("e",e)
		  console.log("scrollTop",this.scrollTop)
		if (e.position === 'left' && e.index === 0) {
		    app.$navigateBack()
		}
        if (e.position === 'right' && e.index === 0) {
			this.create()
		}
      }
    }
  }
</script>

<style>
  
</style>
